<div id='delivery-position-body'>
    <ul id='delivery-position-days'>
        <% for day in range(7) %>
            <% if day == 0 %>
            <li class='active' data-id=${day}>当天</li>
            <% else %>
            <li data-day=${day}>第${day + 1}天</li>
            <% endif %>
        <% endfor %>
    </ul>
    <div>
        <div id="delivery-position-container"></div>
        <div class="position-list">
            <ul id='delivery-position-list' class="delivery-position-list" ></ul>
            <div style="margin:15px 5px"><span class='invisible-position-count'><span>0</span>个已删除</span></div>
            <ul id='invisible-delivery-position-list' class="delivery-position-list" ></ul>
        </div>
    </div>
</div>

<script>
    !(function() {
        // 选择器，如果腾讯地图API已经被加载，那么自动的显示地图
        var serve_api = 'http://map.qq.com/api/js?v=2.exp&callback=window_dilivrey_position_list_container&libraries=convertor'
        var qq_script = document.querySelectorAll("script[src='" + serve_api + "']")
        if (qq_script.length > 0) {
            window_dilivrey_position_list_container();
        } else {
            var script = document.createElement("script");
            script.type = "text/javascript";
            script.src = serve_api;
            document.body.appendChild(script);
        };
    })();

    // 腾讯地图回调函数，需要被暴露在全局对象中
    var window_dilivrey_position_list_container = function() {
        var info = false,
            current_marker = null,
            position_list = $('#delivery-position-list'),
            invisible_position_list = $('#invisible-delivery-position-list'),
            default_interval = {latitude: 31.239776, longitude: 121.499682},  // 默认的地理位置，上海东方明珠塔
            map = create_map(),
            gps_posiiton = [],
            marker_collect = [],
            purchase_marker_collect = [];

        function toggle_marker(marker_index, invisible) {
            var marker = marker_collect[marker_index];
            marker.setMap(invisible? null : map);
        }

        function set_geocoder_marker(line) {
            var position_li = $(create_li_by_line(line));
            if (line.invisible) {
                invisible_position_list.append(position_li)
            } else {
                position_list.append(position_li)
            }

            position_li.find('.cancel-position').on('click', function(event) {
                event.stopPropagation();
                var li = $(this).closest('li');

                invisible_position_list.append(li);
                toggle_marker(li.data('marker_id'), true)
                update_invisible_count();

                $.post('/position/invisible', {
                    id: li.data('id'),
                    invisible: true,
                });
            });

            position_li.find('.uncancel-position').on('click', function(event) {
                event.stopPropagation();
                var li = $(this).closest('li');

                position_list.append(li);
                toggle_marker(li.data('marker_id'), false)
                update_invisible_count();

                $.post('/position/invisible', {
                    id: li.data('id'),
                    invisible: false,
                });
            });

            if (line.address) {
                var geocoder = new qq.maps.Geocoder({
                    complete: function(result) {
                        line.latlng = {latitude: result.detail.location.lat, longitude: result.detail.location.lng}
                        set_marker(line, position_li);
                    },
                    error: function(result) {
                        create_wrong_line(position_li, '无法解析该地址\n' + line.address);
                    }
                });

                geocoder.getLocation(line.address);
            } else {
                create_wrong_line(position_li, '地址信息不存在');
            }
        };

        function update_invisible_count(count) {
            count = count || $('#invisible-delivery-position-list > li').length;
            var widget = $('.invisible-position-count');
            if (count > 0) {
                widget.show();
                widget.find('span').text(count);
            } else {
                widget.hide();
            }
        };

        function create_wrong_line(position_li, title) {
            position_li.addClass('wrong');
            position_li.tooltip({title: title});
            position_list.append(position_li);
        };

        function create_li_by_line(line) {
            return '<li data-id=' + line.id + '><div><strong>' + (line.partner || '') + '(' + line.order + ')</strong></div><span class="cancel-position">X</span><span class="uncancel-position">+</span></li>';
        };

        function create_map(zoom) {
            var myLatlng = new qq.maps.LatLng(default_interval.latitude, default_interval.longitude);
            var myOptions = {
                zoom: zoom || 11,
                center: myLatlng,
                scrollwheel: false,
            };

            var position_container = document.getElementById('delivery-position-container');

            var height = $(window).height() - $('#delivery-position-body > div').offset().top - 10;
            position_container.style.minHeight = height + 'px';  // 设置地图的高度
            // position_list.height(height);  // 设置地图的高度
            $('.position-list').height(height);

            map = new qq.maps.Map(position_container, myOptions);
            info = new qq.maps.InfoWindow({ map: map });

            // 初始化天数标签
            var $day = $('#delivery-position-days > li');
            $day.click(function(e) {
                e.stopPropagation();

                var $this = $(this),
                    days = $this.data('day') || 0;

                $day.removeClass('active');
                $this.addClass('active');

                refresh_position(days);
                refresh_purchase_position(days);
            });

            return map
        };

        function refresh_position(days) {
            marker_collect.forEach(function(marker, index) {
                marker.setMap(null);
            });

            marker_collect.splice(0, marker_collect.length)
            position_list.empty();

            $.when($.get('/position/get_delivery_path', {days: days})).done(function(e) {
                var res = JSON.parse(e);
                res.forEach(function(line) {
                    set_geocoder_marker(line);
                });

                update_invisible_count(res.filter(function(line) { return line.invisible}).length);
                if (res.length === 0) {
                    map = map || create_map();
                }
            });
        };

        function refresh_gps_position() {
            map = map || create_map();

            $.when($.get('/position/last_gps_position')).then(function(res) {
                res = JSON.parse(res);
                if (res.length > 0) {
                    update_gps_position(res);
                }
            }, function(e) {
                console.log('读取GPS平台地理位置信息发生错误，请联系管理员');
            }).always(function() {
                setTimeout(refresh_gps_position, 30000)
            });

        };

        function update_purchase_position(line) {
            if (line.address) {
                var geocoder = new qq.maps.Geocoder({
                    complete: function(result) {
                        line.latlng = {latitude: result.detail.location.lat, longitude: result.detail.location.lng}
                        set_purchase_marker(line);
                    },
                });

                geocoder.getLocation(line.address);
            }
        }

        function refresh_purchase_position(days) {
            purchase_marker_collect.forEach(function(marker, index) {
                marker.setMap(null);
            });

            purchase_marker_collect.splice(0, marker_collect.length)
            invisible_position_list.empty();

            $.when($.get('/position/get_purchase_delivery_path', {days: days})).done(function(e) {
                var res = JSON.parse(e);
                res.forEach(function(line) {
                    update_purchase_position(line);
                });
            });
        }

        function TrackOverlay(position, direction, message) {
            this.position = position;
            this.direction = direction || 0;
            this.message = message || '';
        }

        TrackOverlay.prototype = new qq.maps.Overlay();
        TrackOverlay.prototype.construct = function() {
            var img = $('<img />');
            img.attr('src', '/dftg_ext/static/src/css/truck.png');
            img.css({
                width: '32px',
                height: '32px',
                position: 'absolute',
                cursor: 'pointer',
                transform: 'rotate(' + (this.direction + 90) + 'deg)',
            });

            this.img = img[0];

            var panes = this.getPanes();
            panes.overlayMouseTarget.appendChild(this.img);

            var self = this;
            qq.maps.event.addListener(img[0], 'mouseover', function() {
                info.open();
                info.setContent(self.message);
                info.setPosition(self.position);
            });

            qq.maps.event.addListener(img[0], 'mouseout', function() {
                info.close();
            });
        }

        TrackOverlay.prototype.draw = function() {
            var overlayProjection = this.getProjection();
            //返回覆盖物容器的相对像素坐标
            var pixel = overlayProjection.fromLatLngToDivPixel(this.position);
            var divStyle = this.img.style;
            divStyle.left = pixel.x - 16 + "px";
            divStyle.top = pixel.y - 16 + "px";
        }

        TrackOverlay.prototype.destroy = function() {
            this.img.parentNode.removeChild(this.img);
            this.img = null
        }

        function update_gps_position(records) {
            gps_posiiton.forEach((function(marker) {
                marker.setMap(null);
            }))

            gps_posiiton.splice(0, gps_posiiton.length);

            function _move_message(line) {
                var message = line.vehicle + line.placename;
                if (line.waiting_time) {
                    var minutes = Math.floor(line.waiting_time / 60),
                        seconds = Math.floor(line.waiting_time ${'%'} 60);

                    message += '(停车：' + (minutes > 0? minutes + '分': '') + (seconds > 0? seconds + '秒': '') + ')';
                }

                return message;
            }

            records.forEach(function(line) {
                qq.maps.convertor.translate(new qq.maps.LatLng(line.lat, line.lon), 1, function(res) {
                    var track = new TrackOverlay(res[0], line.direction, _move_message(line));
                    track.setMap(map);

                    gps_posiiton.push(track);
                });

            });
        };

        function set_purchase_marker(line) {
            map = map || create_map();

            var myLatlng = new qq.maps.LatLng(line.latlng.latitude, line.latlng.longitude);
            var marker = new qq.maps.Marker({
                map: map,
                icon: '/dftg_ext/static/src/css/push_pin.png',
            });

            purchase_marker_collect.push(marker);

            marker.setPosition(myLatlng);
            qq.maps.event.addListener(marker, 'mouseover', function() {
                info.open();
                info.setContent(line.line_info);
                info.setPosition(marker.getPosition());
            });

            qq.maps.event.addListener(marker, 'mouseout', function() {
                info.close();
            });
        }

        function set_marker(line, position_li) {
            map = map || create_map();

            var myLatlng = new qq.maps.LatLng(line.latlng.latitude, line.latlng.longitude);
            var marker;
            console.log(line.picking_type_code);
            if (line.picking_type_code == 'outgoing') {
                marker = new qq.maps.Marker();
                if (!line.invisible) {
                    marker.setMap(map);
                }
            } else {
                var anchor = new qq.maps.Point(6, 6),
                    size = new qq.maps.Size(24, 24),
                    bus_icon = new qq.maps.MarkerImage('/dftg_ext/static/src/css/location.png', size, new qq.maps.Point(0, 0), anchor),
                    subway_icon1 = new qq.maps.MarkerImage('/dftg_ext/static/src/css/busmarker.png', size, new qq.maps.Point(48, 0), anchor),
                    subway_icon = new qq.maps.MarkerImage('/dftg_ext/static/src/css/busmarker.png', size, new qq.maps.Point(72, 0), anchor),
                    icon = new qq.maps.MarkerImage('/dftg_ext/static/src/css/busmarker.png', size, new qq.maps.Point(0, 0), anchor);
                marker = new qq.maps.Marker({
                    icon: bus_icon,
                    map: map,
                    position: map.getCenter()
                });
            }
            marker_collect.push(marker);
            position_li.data('marker_id', marker_collect.length - 1);
            position_li.click(function(e) {
                e.stopPropagation();
                map.setCenter(myLatlng);
                $('.position-list li').removeClass('active');
                position_li.addClass('active');

                if (current_marker) {
                    current_marker.setAnimation(null);
                };

                current_marker = marker_collect[position_li.data('marker_id')];
                current_marker.setAnimation(qq.maps.MarkerAnimation.BOUNCE);
            })

            marker.setPosition(myLatlng);
            qq.maps.event.addListener(marker, 'mouseover', function() {
                info.open();
                info.setContent((line.partner || '') + '(' + line.order + ')');
                info.setPosition(marker.getPosition());
            });

            qq.maps.event.addListener(marker, 'mouseout', function() {
                info.close();
            });
        }

        refresh_position();
        refresh_gps_position();
        refresh_purchase_position();
        $('.invisible-position-count').on('click', function(e) {
            invisible_position_list.toggle('slow');
        });
    };

</script>
